package com.jt.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jt.mapper.ItemDescMapper;
import com.jt.mapper.ItemMapper;
import com.jt.pojo.Item;
import com.jt.pojo.ItemDesc;
import com.jt.vo.ItemVO;
import com.jt.vo.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class ItemServiceImpl implements ItemService{
    @Autowired
    private ItemMapper itemMapper;
    @Autowired
    private ItemDescMapper itemDescMapper;

    /**
     * 商品列表展现
     * @param pageResult
     * @return
     */
    @Override
    public PageResult getItemList(PageResult pageResult) {
        boolean flag= StringUtils.hasLength(pageResult.getQuery());
        QueryWrapper<Item> queryWrapper=new QueryWrapper<>();
        queryWrapper.like(flag,"title", pageResult.getQuery());
        IPage<Item> page=new Page<>(pageResult.getPageNum(), pageResult.getPageSize());
        page=itemMapper.selectPage(page,queryWrapper);
        long total=page.getTotal();
        List<Item> rows=page.getRecords();
        return pageResult.setRows(rows).setTotal(total);
    }

    /**
     * 商品新增
     * @param itemVO
     */
    @Override
    @Transactional
    public void saveItem(ItemVO itemVO) {
        Item item=itemVO.getItem().setStatus(true);
        itemMapper.insert(item);
        ItemDesc itemDesc = itemVO.getItemDesc().setId(item.getId());
        itemDescMapper.insert(itemDesc);
    }

    /**
     * 商品删除
     * @param id
     */
    @Override
    @Transactional
    public void deleteItemById(Integer id) {
        itemMapper.deleteById(id);
        itemDescMapper.deleteById(id);
    }

    /**
     * 商品状态修改
     * @param item
     */
    @Override
    public void updateItemStatus(Item item) {
        itemMapper.updateById(item);
    }


}
